const ws = require('nodejs-websocket')
const PORT = 3000

let count = 0;
const server = ws.createServer( connect => {
    count++;
    connect.UserName = `用户${count}`
    // bordercast(connect.UserName+ '进入了聊天室')
    bordercast({
        type: 0,
        msg: connect.UserName+ '进入了聊天室',
        date: new Date().toLocaleDateString()
    })
    connect.on('text', (data) => {
        bordercast(
            {
                type: 1,
                msg: connect.UserName+ '说：'+ data,
                date: new Date().toLocaleDateString()
            }
        )
    })
    connect.on('close', ()=>{
        bordercast({
            type: 2,
            msg: connect.UserName+ '退入了聊天室',
            date: new Date().toLocaleDateString()
        })
    })
    connect.on('error', ()=> {
        console.log('错误处理')
    })
} )
function bordercast(msg){
    var msg = JSON.stringify(msg)
    server.connections.forEach(item => {
        item.send(msg)
    })
}
server.listen(PORT, () => {
    console.log('监听了'+PORT)
} )